<script setup lang='ts'>
import type { flashIndexParam } from '@fl/api/advertising-api/model/flash-management-types'
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { exportNews, useAreaList, useFlashDelete, useFlashSwitchStatus, useLabelEnableList, useLandPolicyIndex, useSortEnableList } from '@fl/api/advertising-api/flash-management'
import { SearchForm, SearchTable } from '@fl/components'
import { formatTime } from '@fl/utils'
import { cloneDeep } from 'lodash-es'
import { reactive } from 'vue'

import addOrEditBox from './component/addLandPolicyOrEdit.vue'
import showBox from './component/showLandPolicy.vue'
import { useDicts } from './hooks/use-dicts'

const tableRef = ref()
const { dicts: { IsOrNot, ShowOnStatus }, useDict } = useDicts()

const visible = ref<boolean>(false)
const showVisible = ref<boolean>(false)
const editId = ref<string>('')
const showId = ref<string>('')
const sortOptions = ref<any>()
const sortDict = ref<any>()
const tableHeight = ref<number>(550)

// 搜索条件、分页参数
const initialState = {
    areaCode: '',
    choiceFlag: '', // 0-非精选 1-精选
    classifyId: '',
    createTime: ['', ''],
    delFlag: '',
    draftFlag: '',
    newsTitle: '',
}
const state = ref<flashIndexParam>(cloneDeep(initialState))
const tablePage = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const initialPage = toRaw({ ...tablePage.value })

// 查询列表
const params = computed(() => ({
    areaCode: state.value.areaCode || null,
    choiceFlag: state.value.choiceFlag || null,
    classifyId: state.value.classifyId || null,
    delFlag: state.value.delFlag || null,
    draftFlag: state.value.draftFlag || null,
    endTime: state.value.createTime?.[1] ? formatTime(state.value?.createTime[1], 'yyyy-MM-dd 23:59:59') : null,
    newsTitle: state.value.newsTitle || null,
    newsTypeIds: '2,4', // 业务类型（1-安居快讯 2-土拍政策 3-保租房公告，4-土拍推介）
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    startTime: state.value.createTime?.[0] ? formatTime(state.value?.createTime[0], 'yyyy-MM-dd 00:00:00') : null,
}))
const { data, isLoading, refetch } = useLandPolicyIndex(params)
function queryList() {
    refetch()
}
const records = ref()
watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.records).reduce((pre, cur) => {
            if (cur.labelsList) {
                cur.labels = cur.labelsList.reduce((pre2, cur2) => {
                    pre2 += `${cur2.labelName},`
                    return pre2
                }, '')
                cur.labels = cur.labels.substring(0, cur.labels.length - 1)
            }
            else {
                cur.labels = ''
            }
            // 发布时间作为判断已上架的一个条件
            const createTimeNum = new Date(cur.createTime).getTime()
            const currentTimeNum = new Date().getTime()
            cur.isTimeArrived = createTimeNum < currentTimeNum
            pre.push(cur)
            return pre
        }, [])
        // console.log('处理后', records.value)
        tablePage.value.total = data.value.total!
    }
})

// 分类、标签列表
const { data: sortList } = useSortEnableList()
watchEffect(() => {
    if (sortList.value) {
        const rows = cloneDeep(sortList.value)
        if (rows.length > 0) {
            sortOptions.value = rows.reduce((pre, cur) => {
                cur.value = cur.id
                cur.label = cur.classifyName
                pre.push(cur)
                return pre
            }, [])
            sortDict.value = sortOptions.value.reduce((accumulator, current) => {
                accumulator[current.value] = current.label
                return accumulator
            }, [])
        }
    }
})

// 删除
const { mutate: deleteMutate } = useFlashDelete()

// 搜索
function submit(values: flashIndexParam) {
    state.value = { ...values }
    tablePage.value.currentPage = 1
}

// 重置
function reset() {
    state.value = initialState
    tablePage.value = initialPage
}

// 新增
function goToAdd() {
    visible.value = true
}

// 列表：查看
function goToShow(row: any) {
    showVisible.value = true
    showId.value = row?.id
}

// 列表：编辑
function goToEdit(row: any) {
    visible.value = true
    editId.value = row?.id
}

async function exportExcel() {
    const exportParams = {
        choiceFlag: state.value.choiceFlag ? state.value.choiceFlag : '',
        classifyId: state.value.classifyId ? state.value.classifyId : '',
        delFlag: state.value.delFlag ? state.value.delFlag : '',
        newsTitle: state.value.newsTitle ? state.value.newsTitle : '',
        newsTypeId: 2, // 业务类型（1-安居快讯 2-土拍政策 3-保租房公告）
        pageNum: 1,
        pageSize: 2000,
    }
    const result = await exportNews(exportParams)
    const blob = new Blob([result], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const objectUrl = URL.createObjectURL(blob)
    location.href = objectUrl
    URL.revokeObjectURL(objectUrl)
}

// 列表：删除
function deleteConfirm(row: any) {
    deleteMutate(row.id, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

// 切换展示、隐藏
const { mutate: switchStatusMutate } = useFlashSwitchStatus()
// function switchStatus(row: any) {
//     switchStatusMutate(row.id, {
//         onSuccess: () => {
//             ElMessage.success('操作成功')
//         },
//     })
// }

// 下架
function goDown(row: any) {
    switchStatusMutate(row.id, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

const districtTypes = ref([])
const areaDict = ref([])
// 分类、标签列表
const { data: areaDataList } = useAreaList()
watchEffect(() => {
    if (areaDataList.value) {
        const rows = cloneDeep(areaDataList.value)
        const cityList = rows.data
	    const targetCity = cityList.find((item) => {
            return item.areaName == '武汉市'
        })
        districtTypes.value = targetCity.children
        districtTypes.value.map((it) => {
            it.value = it.areaCode
            it.label = it.areaName
            return it
        })

        areaDict.value = districtTypes.value.reduce((item, current) => {
            item[current.areaCode] = current.label
            return item
        }, [])
    }
})

const columns: PlusColumn[] = [
    {
        label: '标题',
        prop: 'newsTitle',
        valueType: 'copy',
    },
    {
        fieldProps: {
            'endPlaceholder': '结束时间',
            'startPlaceholder': '开始时间',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD',
        },
        label: '发布日期',
        prop: 'createTime',
        valueType: 'date-picker',
    },
    {
        label: '状态',
        options: ShowOnStatus,
        prop: 'draftFlag',
        valueType: 'select',
    },
    {
        label: '所属区域',
        options: computed(() => {
            return districtTypes.value
        }),
        prop: 'areaCode',
        valueType: 'select',
    },
]
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 50 },
        { field: 'id', minWidth: 180, title: '土拍政策ID' },
        { field: 'titleImage', minWidth: 110, slots: { default: 'titleImage' }, title: '图片' },
        { field: 'newsTitle', minWidth: 100, title: '标题' },
        { field: 'createBy', minWidth: 100, title: '发布者' },
        { field: 'createTime', minWidth: 160, title: '发布时间' },
        { field: 'newsTypeId', minWidth: 120, slots: { default: 'newsType' }, title: '业务类型' },
        { field: 'areaName', minWidth: 100, title: '所属区域' },
        // { field: 'topFlag', minWidth: 100, slots: { default: 'topFlag' }, title: '置顶' },
        // { field: 'topTime', minWidth: 160, slots: { default: 'topTime' }, title: '置顶时间' },
        // { field: 'viewNum', minWidth: 100, title: '浏览量' },
        // { field: 'upNum', minWidth: 100, title: '点赞数' },
        // { field: 'commentsNum', minWidth: 100, title: '评论' },
        { field: 'draftFlag', minWidth: 90, slots: { default: 'draftFlag' }, title: '状态' },
        // { field: 'delFlag', minWidth: 90, slots: { default: 'delFlag' }, title: '状态' },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 150 },
    ],
})
</script>

<template>
    <ElCard class="mb-20"
            shadow="never"
    >
        <SearchForm v-bind="state"
                    :columns="columns"
                    submit-text="搜索"
                    @reset="reset"
                    @submit="submit"
        />
    </ElCard>

    <ElCard shadow="never">
        <SearchTable ref="tableRef"
                     v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :seq-config="{ startIndex: (tablePage.currentPage - 1) * tablePage.pageSize }"
                     :loading="isLoading"
                     :data="records"
                     :row-config="{ height: 100 }"
                     :height="tableHeight"
                     @page-change="handlePageChange"
        >
            <template #titleImage="{ row }">
                <el-image v-if="row.titleImage"
                          style="width: 80px; height: 80px"
                          :src="row.titleImage"
                          :zoom-rate="1.2"
                          :max-scale="7"
                          :min-scale="0.2"
                          :preview-src-list="[row.titleImage]"
                          :initial-index="4"
                          fit="contain"
                />
            </template>

            <template #classifyId="{ row }">
                {{ row.classifyName }}
            </template>

            <template #originalFlag="{ row }">
                {{ row.originalFlag === '1' ? '原创' : '外部链接' }}
            </template>

            <template #topFlag="{ row }">
                {{ useDict('IsOrNot', row.topFlag) }}
            </template>

            <template #topTime="{ row }">
                {{ row.topFlag === '1' ? `${row.topStartTime} 至 ${row.topEndTime}` : '' }}
            </template>

            <template #choiceFlag="{ row }">
                {{ useDict('IsOrNot', row.choiceFlag) }}
            </template>

            <template #draftFlag="{ row }">
                <div v-if="row.draftFlag === '0'">
                    未上架
                </div>

                <div v-else>
                    已上架
                </div>
            </template>

            <template #newsType="{ row }">
                <div v-if="row.newsTypeId === '2'">
                    土拍政策
                </div>

                <div v-if="row.newsTypeId === '4'">
                    土地推介
                </div>
            </template>

            <template #toolbar_buttons>
                <ElButton type="primary"
                          @click="goToAdd"
                >
                    <div class="i-ic:baseline-add size-16" />
                    发布土拍政策
                </ElButton>
            </template>

            <template #operate="{ row }">
                <el-button class="small"
                           type="info"
                           text
                           @click="goToShow(row)"
                >
                    查看
                </el-button>

                <el-button class="small"
                           type="primary"
                           text
                           @click="goToEdit(row)"
                >
                    编辑
                </el-button>

                <el-button v-if="row.draftFlag === '1'"
                           class="small"
                           type="primary"
                           text
                           @click="goDown(row)"
                >
                    下架
                </el-button>

                <!-- <el-popconfirm title="确认删除吗？" @confirm="deleteConfirm(row)">
                    <template #reference>
                        <el-button class="small" text type="warning">
                            删除
                        </el-button>
                    </template>
                </el-popconfirm> -->
            </template>
        </SearchTable>
    </ElCard>

    <addOrEditBox v-model:visible="visible"
                  v-model:id="editId"
                  :sort-options="sortOptions"
                  :sort-dict="sortDict"
                  :area-dict="areaDict"
                  @query="queryList"
    />

    <showBox v-model:visible="showVisible"
             v-model:id="showId"
             :sort-options="sortOptions"
    />
</template>

<style lang="scss" scoped>
:deep(.small.el-button) {
    padding: 4px;
    margin-left: 6px;
}
</style>
